import uuid
from datetime import datetime
from django.shortcuts import render
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Order, OrderItem, ORDER_STATUS_CHOICES  # 添加ORDER_STATUS_CHOICES导入
from .serializers import OrderSerializer
from product.models import Product
import django.db.models as models  # 添加这行导入

class OrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    # 只允许用户查看自己的订单
    def get_queryset(self):
        user = self.request.user
        # 获取搜索关键词
        search = self.request.query_params.get('search', None)
        
        # 管理员可以查看所有订单
        if user.user_type == 'admin' or user.is_superuser:
            queryset = Order.objects.all()
        else:
            # 普通用户只能查看自己的订单
            queryset = Order.objects.filter(user=user)
        
        # 如果有搜索关键词，根据订单号或用户名进行过滤
        if search:
            queryset = queryset.filter(
                models.Q(order_number__icontains=search) | 
                models.Q(user__username__icontains=search)
            )
        
        return queryset
    
    # 生成唯一订单号
    def generate_order_number(self):
        now = datetime.now()
        date_str = now.strftime('%Y%m%d')
        random_str = uuid.uuid4().hex[:8].upper()
        return f'ORD-{date_str}-{random_str}'
    
    # 创建订单
    def create(self, request, *args, **kwargs):
        try:
            # 从request.data中获取'order_items'
            order_items = request.data.get('order_items', [])
            
            if not order_items:
                return Response({'error': '购物车不能为空'}, status=status.HTTP_400_BAD_REQUEST)
            
            # 创建订单时直接设置一个默认的total_price值
            order = Order.objects.create(
                order_number=self.generate_order_number(),
                user=request.user,
                status='pending',
                total_price=0.00,
                shipping_address=request.data.get('shipping_address', ''),
                contact_phone=request.data.get('contact_phone', '')
            )
            
            total_price = 0
            
            # 创建订单项
            for item_data in order_items:
                product_id = item_data.get('product_id')
                quantity = item_data.get('quantity', 1)
                
                try:
                    product = Product.objects.get(id=product_id)
                    # 创建订单项，存储商品的当前信息
                    order_item = OrderItem.objects.create(
                        order=order,
                        product=product,
                        product_name=product.name,
                        product_price=product.price,
                        product_image=product.image.url if product.image else '',
                        quantity=quantity,
                        subtotal=product.price * quantity
                    )
                    
                    total_price += order_item.subtotal
                except Product.DoesNotExist:
                    # 删除已创建的订单
                    order.delete()
                    return Response({'error': f'商品ID {product_id} 不存在'}, status=status.HTTP_404_NOT_FOUND)
            
            # 更新订单总价
            order.total_price = total_price
            order.save()
            
            # 返回创建的订单
            serializer = OrderSerializer(order)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    # 修复缩进，确保这个方法在OrderViewSet类内部
    @action(detail=True, methods=['post'], permission_classes=[permissions.IsAuthenticated])
    def change_status(self, request, pk=None):
        # 获取订单实例
        order = self.get_object()
        new_status = request.data.get('status')
        
        # 检查用户权限
        if request.user.user_type != 'admin' and request.user != order.user:
            return Response({'error': '无权修改此订单状态'}, status=status.HTTP_403_FORBIDDEN)
        
        # 验证新的订单状态是否有效
        valid_statuses = [choice[0] for choice in ORDER_STATUS_CHOICES]
        if new_status not in valid_statuses:
            return Response({'error': '无效的订单状态'}, status=status.HTTP_400_BAD_REQUEST)
        
        # 更改订单状态
        order.status = new_status
        order.save()
        
        # 返回更新后的订单数据
        serializer = OrderSerializer(order)
        return Response(serializer.data)
